if (app.documents.length === 0) {
    alert("请先打开一个文档。");
} else {
    app.doScript(function () {
        var doc = app.activeDocument;

        // ===== 样式收集（含分组路径名）=====
        function getAllObjectStylesWithPaths(styleGroup, pathPrefix, resultList, styleMap) {
            var styles = styleGroup.objectStyles;
            for (var i = 0; i < styles.length; i++) {
                var style = styles[i];
                if (style.name !== "[Normal Object Style]") {
                    var fullName = pathPrefix + style.name;
                    resultList.push(fullName);
                    styleMap[fullName] = style;
                }
            }
            var groups = styleGroup.objectStyleGroups;
            for (var j = 0; j < groups.length; j++) {
                var group = groups[j];
                getAllObjectStylesWithPaths(group, pathPrefix + group.name + "/", resultList, styleMap);
            }
        }

        var objectStyleNames = [];
        var objectStyleMap = {};
        getAllObjectStylesWithPaths(doc, "", objectStyleNames, objectStyleMap);

        // ===== 对话框 =====
        var dialog = app.dialogs.add({ name: "复制线条/多边形并更换样式（独立 + 组直接子对象）" });
        var sourceDropdown, targetDropdown, onlySelCB;
        with (dialog.dialogColumns.add()) {
            sourceDropdown = dropdowns.add({
                stringList: objectStyleNames, selectedIndex: 0, minWidth: 220, staticLabel: "原样式"
            });
            targetDropdown = dropdowns.add({
                stringList: objectStyleNames, selectedIndex: 0, minWidth: 220, staticLabel: "目标样式"
            });
            onlySelCB = checkboxControls.add({
                staticLabel: "仅处理当前选区（组：仅直接子对象）", checkedState: false
            });
        }
        if (!dialog.show()) { dialog.destroy(); return; }
        var sourceStyleName = sourceDropdown.stringList[sourceDropdown.selectedIndex];
        var targetStyleName = targetDropdown.stringList[targetDropdown.selectedIndex];
        var onlySelection = onlySelCB.checkedState;
        dialog.destroy();

        var sourceStyle = objectStyleMap[sourceStyleName];
        var targetStyle = objectStyleMap[targetStyleName];
        if (!sourceStyle || !sourceStyle.isValid || !targetStyle || !targetStyle.isValid) { alert("所选样式无效。"); return; }
        if (sourceStyle === targetStyle) { alert("原样式和目标样式不能相同。"); return; }

        // ===== 工具函数 =====
        function isProcessable(pi) {
            try {
                if (!pi || !pi.isValid) return false;
                if (pi.locked) return false;
                if (pi.itemLayer && pi.itemLayer.locked) return false;
                return true;
            } catch (e) { return false; }
        }

        var count = 0;
        function tryDuplicateChangeStyle(it) {
            if (!isProcessable(it)) return;
            try {
                if (it.appliedObjectStyle === sourceStyle) {
                    var dup = it.duplicate(); // 原位复制；若在组内，会留在同一组
                    dup.appliedObjectStyle = targetStyle;
                    count++;
                }
            } catch (eDup) {}
        }

        // ===== 处理独立对象（非组内）=====
        function processIndependentIn(container) {
            // container 为 doc 或 layer 等，使用其 collections 读取
            var lines = container.graphicLines;
            for (var i = lines.length - 1; i >= 0; i--) {
                var ln = lines[i];
                if (!(ln.parent instanceof Group)) tryDuplicateChangeStyle(ln);
            }
            var polys = container.polygons;
            for (var j = polys.length - 1; j >= 0; j--) {
                var pg = polys[j];
                if (!(pg.parent instanceof Group)) tryDuplicateChangeStyle(pg);
            }
        }

        // ===== 处理某个组的“直接子对象”=====
        function processGroupDirectChildren(grp) {
            if (!isProcessable(grp)) return;

            // 仅取 parent === grp 的直接子项
            var gls = grp.graphicLines;
            for (var i = gls.length - 1; i >= 0; i--) {
                var ln = gls[i];
                if (ln.parent === grp) tryDuplicateChangeStyle(ln);
            }
            var pgs = grp.polygons;
            for (var j = pgs.length - 1; j >= 0; j--) {
                var pg = pgs[j];
                if (pg.parent === grp) tryDuplicateChangeStyle(pg);
            }
        }

        // ===== 整文档：独立对象 + 各组的直接子对象 =====
        function processWholeDocument() {
            processIndependentIn(doc);

            var groups = doc.groups; // 包含所有层级的组
            for (var g = 0; g < groups.length; g++) {
                processGroupDirectChildren(groups[g]);
            }
        }

        // ===== 选区：选中的独立线/多边形 + 选中的组的直接子对象 =====
        function processSelection() {
            var sel = app.selection;
            if (!sel || sel.length === 0) { alert("没有选区。"); return; }

            var seen = {};
            function markSeen(pi) { try { if (pi && pi.isValid) seen[pi.id] = true; } catch (e) {} }
            function notSeen(pi) { try { return !(pi && pi.isValid && seen[pi.id]); } catch (e) { return false; } }

            for (var s = 0; s < sel.length; s++) {
                var o = sel[s];

                // 若是组：处理其直接子对象
                if (o instanceof Group) {
                    processGroupDirectChildren(o);
                    continue;
                }

                // 若是线/多边形：直接处理它本身（无论是否在组内）
                try {
                    var cn = o && o.constructor ? o.constructor.name : "";
                    if (cn === "GraphicLine" || cn === "Polygon") {
                        if (notSeen(o)) { markSeen(o); tryDuplicateChangeStyle(o); }
                        continue;
                    }
                } catch (e0) {}

                // 其他类型忽略（不递归展开，以免重）
            }
        }

        if (onlySelection) {
            processSelection();
            alert("完成（选区）。已复制并改样式数量： " + count);
        } else {
            processWholeDocument();
            alert("完成（整文档：独立对象 + 组直接子对象）。已复制并改样式数量： " + count);
        }

    }, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "复制并换样式（独立+组直接子对象）");
}
